package com.duowan.cms.intf.tougao;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.duowan.cms.common.exception.BaseCheckedException;
import com.duowan.cms.common.util.IdManager;
import com.duowan.cms.common.util.StringUtil;
import com.duowan.cms.common.webapp.content.SpringApplicationContextHolder;
import com.duowan.cms.common.webapp.property.ExtendedPropertyPlaceholderConfigurer.PropertiesHolder;
import com.duowan.cms.core.rmi.client.article.ArticleRemoteService;
import com.duowan.cms.core.rmi.client.channel.ChannelRemoteService;
import com.duowan.cms.dto.article.ArticleInfo;
import com.duowan.cms.dto.article.ArticleStatus;
import com.duowan.cms.dto.channel.ChannelInfo;
import com.duowan.cms.intf.util.IPFilter;

public class TougaoArticleServlet extends HttpServlet {

    private static final long serialVersionUID = 4621640872689325948L;
    private static final Logger logger = Logger.getLogger(TougaoArticleServlet.class);

    private static final String CODE_SUCCESS = "201";

    private static final String CODE_IP_DENIED = "410";

    private static final String CODE_ERROR_PARAMETER = "401";

    private static final String CODE_SERVER_ERROR = "500";

    // private static final String CODE_OTHER_ERROR = "504";

    private static final String OPERATE_TYPE = "addArticle";
    private static final String TOUGAOARTICLE_ALLOWEDIP = "ip_tougaoArticle";
    private static final String ARTICLE_TAGS = "article_tag";
    private static final String DEFAULT_TEMPLATEID = "article_templateid";
    private static final String DEFAULT_USERID = "default_userid";
    private static final String DEFAULT_CHANNELID = "channelid";

    /**
     * 
     * 处理GET请求
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    /**
     * 处理POST请求
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/plain");
            request.setCharacterEncoding("UTF-8");

            // 添加IP限制
            String ip = request.getHeader("X-Forwarded-For");
            if (StringUtil.isEmpty(ip)) {
                ip = request.getRemoteAddr();
            }
            ip = ip.split(", ")[0].trim();
            if ("127.0.0.1".equals(ip)) {
                ip = request.getRemoteAddr();
            }
            if (!IPFilter.isLegalIp(ip, TOUGAOARTICLE_ALLOWEDIP)) {
                logger.warn("the remote ip:" + ip + " is not allowed to use this interface.");
                String responseStr = generateErrorResonse(CODE_IP_DENIED, "you are not allowed to use this interface");
                response.getWriter().write(responseStr);
                return;
            }

            //TougaoRemoteService tougaoService = SpringApplicationContextHolder.getBean("tougaoRemoteService", TougaoRemoteService.class);
            ArticleRemoteService articleRemoteService = SpringApplicationContextHolder.getBean("articleRemoteService", ArticleRemoteService.class);
            ChannelRemoteService channelRemoteService = SpringApplicationContextHolder.getBean("channelRemoteService", ChannelRemoteService.class);
            ArticleInfo articleInfo = new ArticleInfo();
            // 填充articleInfo,返回有无出错信息
            String fill_article_msg = fillArticleInfo(request, articleInfo, articleRemoteService, channelRemoteService);

            if (!CODE_SUCCESS.equals(fill_article_msg)) {
                logger.warn(fill_article_msg);
                String responseStr = generateErrorResonse(CODE_ERROR_PARAMETER, fill_article_msg);
                response.getWriter().write(responseStr);
                return;
            }

            String responseStr;
            String msg = "";
            try{
                articleRemoteService.publish(articleInfo);
                String url = articleRemoteService.getArticleUrl(articleInfo.getChannelInfo().getId(), articleInfo.getId());
                msg = "success to add article.url :" + url;
                logger.info(msg);
                responseStr = generateSuccessResonse(CODE_SUCCESS, url);
            } catch (BaseCheckedException ex) {
                msg = "fail to add article.";
                logger.error(msg);
                responseStr = generateErrorResonse(CODE_SERVER_ERROR, msg);
            }
            response.getWriter().write(responseStr);
        } catch (Exception e) {
            String responseStr = generateErrorResonse(CODE_SERVER_ERROR, e.getMessage());
            response.getWriter().write(responseStr);
            logger.warn("出错了。。", e);
        }

    }

    private String fillArticleInfo(HttpServletRequest request, ArticleInfo articleInfo, ArticleRemoteService articleRemoteService, ChannelRemoteService channelRemoteService) throws Exception {
        //操作类型要为addArticle
        if (!OPERATE_TYPE.equals(request.getParameter("operate_type"))) {
            return "the [operate_type] is not correct.";
        }
        
        //生成文章id
        long articleid = IdManager.generateId();
        //频道和标题--需要检查已存在该标题
        String channelid = request.getParameter("channel");
        if (StringUtil.isEmpty(channelid)) {
            channelid = PropertiesHolder.get(DEFAULT_CHANNELID, "news");
            logger.info("---------channelid:" + channelid);
        }
        String title = request.getParameter("title");
        if (articleRemoteService.checkTitleIsExisted(channelid, null, title)) {
            return "该文章已存在!" + title;
        }
        //标签与模板
        String tags = PropertiesHolder.get(ARTICLE_TAGS, "厂商,");//new String(ConfigPropertiesUtil.getConfigValue(ARTICLE_TAGS).getBytes("ISO-8859-1"), "UTF-8");
        String tmpId = request.getParameter("template");
        long templateId;
        if (!StringUtil.isEmpty(tmpId)) {
            templateId = Long.parseLong(tmpId);
            logger.info("---------templateId:" + templateId);
        } else {
            templateId = Long.parseLong(PropertiesHolder.get(DEFAULT_TEMPLATEID, "137602142933"));
        }
        //文章其他属性：内容,相关游戏,用户名...
        String content = request.getParameter("content");
        
        String relateGame = request.getParameter("relate_game");
        String userid = request.getParameter("userid");
        String subtitle = "&&";
        if (!StringUtil.isEmpty(relateGame)) {
            tags += relateGame + ",";
            subtitle += relateGame;
        }
        if (StringUtil.isEmpty(userid)) {
            userid = PropertiesHolder.get(DEFAULT_USERID, "蔡鑫松");//new String(PropertiesHolder.get(DEFAULT_USERID, "蔡鑫松").getBytes("ISO-8859-1"), "UTF-8");
        }
        logger.info("add article to tag :" + tags + ",subtitle:" + subtitle + ",related_game:" + relateGame + ",userid:" + userid);
        if (StringUtil.hasOneEmpty(title, content)) {
            return "the [title | content] is empty.";
        }

        
        ChannelInfo channelInfo = channelRemoteService.getById(channelid);
        if(null == channelInfo){
            return "发布器没有此频道：" + channelid;
        }
        articleInfo.setChannelInfo(channelInfo);
        articleInfo.setId(articleid);// 第1个
        articleInfo.setTitle(title);// 第2个
        articleInfo.setSubtitle(subtitle);// 第3个
        articleInfo.setDigest("");// 第4个
        articleInfo.setPictureUrl("");// 第5个
        articleInfo.setSource("官方");// 第6个
        articleInfo.setAuthor("官方");// 第7个
        articleInfo.setPrePublishTime(null);// 第8个
        articleInfo.setTags(tags);// 第9个
        articleInfo.setUserId(userid);// 第10个
        articleInfo.setUserIp("");// 第11个
        articleInfo.setProxyIp("");// 第12个
        articleInfo.setContent(content);// 第13个
        articleInfo.setPower(60);// 第14个
        //articleInfo.setNeedComment(false);// 第15个
        articleInfo.setNeedComment(true);
        Long threadId = 0L;
        if(articleInfo.isNeedComment()){
            threadId = articleInfo.getId();
        }
        articleInfo.setThreadId(threadId);
        articleInfo.setCommentUrl("");// 第16个
        articleInfo.setTemplateId(templateId);// 第17个
        articleInfo.setLogs("");
        articleInfo.setDiy1("");
        articleInfo.setDiy2("");
        articleInfo.setDiy3("");
        articleInfo.setIsSyncWap("off");
        //投稿文章的状态设置为"用户投递的文章",数据库中值为4
        articleInfo.setStatus(ArticleStatus.USER_DELIVERY);
        // 把文章相关的游戏名持久化，放进表ku_article_game
        articleInfo.setRelateGame(relateGame == null ? "" : relateGame);
        // 把文章相关的视频url持久化，放进表article_videoinfo.(注：已经废弃!)
        // p.addString("playurl", "");

        return CODE_SUCCESS;
    }

    /**
     * 返回出错的消息数据
     * 
     * @return
     */
    private String generateErrorResonse(String code, String description) {
        StringBuffer sb = new StringBuffer();
        sb.append(code).append("\n");
        sb.append(description);
        return sb.toString();
    }

    /**
     * 返回正确的消息数据
     * 
     * @return
     */
    private String generateSuccessResonse(String code, String info) {
        StringBuffer sb = new StringBuffer();
        sb.append(code).append("\n");
        sb.append("manage article successfully!").append("\n");
        sb.append("\n");
        sb.append(info);
        return sb.toString();
    }
}
